package com.example.management.common.redis.shiro

import com.sun.org.apache.bcel.internal.generic.IFEQ
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.dao.DataAccessException
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.data.redis.core.StringRedisTemplate
import java.util.concurrent.TimeUnit
import org.springframework.data.redis.connection.RedisConnection
import org.springframework.data.redis.core.RedisCallback




class RedisManager {

    @Autowired
    var redisTemplate: StringRedisTemplate? = null;

//    @Value("\${spring.redis.host}")
//    var host = "127.0.0.1";
//
//    @Value("\${spring.redis.port}")
//    var port = 6379;
//    // 0 - never expire
    var expire = 0L;
//
//    //timeout for jedis try to connect to redis server, not expire time! In milliseconds
//    @Value("\${spring.redis.timeout}")
//   var timeout = 0;
//
//    @Value("\${spring.redis.password}")
//    var password = "";



    /**
     * get value from redis
     *
     * @param key
     * @return
     */

    fun get(byteArray: String):String{
        var value = redisTemplate!!.opsForValue().get(byteArray)
        return value!!;
    }


    fun set(key: String,value:String):String {
        redisTemplate!!.opsForValue().set(key,value,this.expire,TimeUnit.SECONDS)
        return value
    }

    /**
     * set
     *
     * @param key
     * @param value
     * @param expire
     * @return
     */

    fun set(key: String,value:String,expire:Int):String {
        this.expire = expire.toLong()
        val value = set(key,value)
        this.expire = 0L
        return value
    }
    /**
     * del
     *
     * @param key
     */
    fun del(key: String){
        redisTemplate!!.delete(key)
    }

    /**
     * flush
     */
    fun flushDB() {
         redisTemplate!!.execute(RedisCallback {
            fun doInRedis(connection : RedisConnection) {
                return connection.flushDb()

            }
        })
    }

    /**
     * size
     */
    fun dbSize(): Long {

         redisTemplate!!.execute(RedisCallback(){
           fun doInRedis(connection : RedisConnection) : Long {
               val dbSize = connection.dbSize()
               return dbSize()
           }
        })
        return  0L
    }

    /**
     * keys
     *
     * @param regex
     * @return
     */
    fun keys(pattern:String) :Set<String>{
        val keys1 = redisTemplate!!.keys(pattern)

        return keys1
    }

}
